package com.danger.Activity;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.danger.Model.bean.ObjectInfo;
import com.danger.Model.bean.UserInfo;
import com.danger.Presenter.AddMyObjectInfoPresenter;
import com.danger.Presenter.AddMyObjectInfoPresenterImpl;
import com.danger.View.AddMyObjectInfoView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;

public class AddMyFoundActivity extends AppCompatActivity implements AddMyObjectInfoView, View.OnClickListener {

    private EditText found_title_editText;
    private EditText found_describe_editText;
    private Spinner found_category_spinner;
    private Spinner found_address_spinner;
    private Button found_time_button;
    private ImageView found_photo_imageView;
    private Button found_choose_photo_button;
    private Button add_myfound_button;
    private Button found_upload_photo_button;
    private ProgressDialog dialog;
    private AddMyObjectInfoPresenter presenter;
    private String category;
    private String address;
    private String photo;
    private BmobDate date;
    private String url;
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_my_found);
        initView();
        initEvent();
    }

    private void initView() {
        dialog = new ProgressDialog(this);
        dialog.setMessage("正在执行...");
        toolbar = (Toolbar) findViewById(R.id.add_myfound_toolbar);
        toolbar.setTitle("添加招领");
        toolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(toolbar);
        presenter = new AddMyObjectInfoPresenterImpl(this, this);
        found_title_editText = (EditText) findViewById(R.id.found_title_editText);
        found_describe_editText = (EditText) findViewById(R.id.found_describe_editText);
        found_category_spinner = (Spinner) findViewById(R.id.found_category_spinner);
        found_address_spinner = (Spinner) findViewById(R.id.found_address_spinner);
        found_time_button = (Button) findViewById(R.id.found_time_button);
        found_photo_imageView = (ImageView) findViewById(R.id.found_photo_imageView);
        found_choose_photo_button = (Button) findViewById(R.id.found_choose_photo_button);
        add_myfound_button = (Button) findViewById(R.id.add_myfound_button);
        found_upload_photo_button = (Button) findViewById(R.id.found_upload_photo_button);
    }

    private void initEvent() {
        found_category_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                category = (String) found_category_spinner.getSelectedItem();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        found_address_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                address = (String) found_address_spinner.getSelectedItem();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        found_time_button.setOnClickListener(this);
        found_choose_photo_button.setOnClickListener(this);
        add_myfound_button.setOnClickListener(this);
        found_upload_photo_button.setOnClickListener(this);
    }


    @Override
    public void showDialog() {
        dialog.show();
    }

    @Override
    public void hideDialog() {
        dialog.hide();
        dialog.dismiss();
    }

    @Override
    public void showSuccess(String s, String content) {
        if (content != null) {
            url = content;
        }
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showError(String error) {
        Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
    }

    @Override
    public ObjectInfo getObjectInfo() {
        UserInfo data = BmobUser.getCurrentUser(this, UserInfo.class);
        ObjectInfo found = new ObjectInfo();
        found.setLost(false);
        found.setName(data.getUsername());
        found.setPhone(data.getMobilePhoneNumber());
        found.setQq(data.getQq());
        found.setTitle(found_title_editText.getText().toString());
        found.setDescribe(found_describe_editText.getText().toString());
        found.setCategory(category);
        found.setAddress(address);
        if (url != null) {
            found.setPhoto(url);
        }
        if (date != null) {
            found.setDate(date);
        } else {
            Date _date = new Date();
            date = new BmobDate(_date);
            found.setDate(date);
        }
        return found;
    }

    @Override
    public void back() {
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.found_time_button:
                lostDateChoose();
                break;
            case R.id.found_choose_photo_button:
                choose();
                break;
            case R.id.add_myfound_button:
                presenter.addObjectInfo();
                break;
            case R.id.found_upload_photo_button:
                if (photo != null) {
                    presenter.uploadPhoto(photo);
                } else {
                    showError("没有选择照片");
                }
                break;
            default:
                break;
        }
    }

    private void lostDateChoose() {
        final Calendar calendar = Calendar.getInstance();
        DatePickerDialog.OnDateSetListener datestartListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                // Calendar月份是从0开始,所以month要加1
                String content = year + "-" + month + "-" + dayOfMonth;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                try {
                    Date _date = sdf.parse(content);
                    found_time_button.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                    date = new BmobDate(_date);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        DatePickerDialog dialog = new DatePickerDialog(this, ProgressDialog.THEME_HOLO_LIGHT, datestartListener,
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    private void choose() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            /**
             * 当选择的图片不为空的话，在获取到图片的途径
             */
            Uri uri = data.getData();
            Log.e("TAG", "uri = " + uri);
            try {
                String[] pojo = {MediaStore.Images.Media.DATA};

                Cursor cursor = managedQuery(uri, pojo, null, null, null);
                if (cursor != null) {
                    ContentResolver cr = this.getContentResolver();
                    int colunm_index = cursor
                            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String path = cursor.getString(colunm_index);
                    /***
                     * 这里加这样一个判断主要是为了第三方的软件选择，比如：使用第三方的文件管理器的话，你选择的文件就不一定是图片了，
                     * 这样的话，我们判断文件的后缀名 如果是图片格式的话，那么才可以
                     */
                    if (path.endsWith("jpg") || path.endsWith("png")) {
                        photo = path;
                        Bitmap bitmap = BitmapFactory.decodeStream(cr
                                .openInputStream(uri));
                        found_photo_imageView.setImageBitmap(bitmap);
                    } else {
                        alert();
                    }
                } else {
                    alert();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void alert() {
        Dialog dialog = new AlertDialog.Builder(this).setTitle("提示")
                .setMessage("您选择的不是有效的图片")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        photo = null;
                    }
                }).create();
        dialog.show();
    }
}
